package main

import (
    "flag"
    "fmt"
    "os"
    "regexp"
    . "scanner"
    "sort"
)

var (
    srcFile, mergeFile, outputFile string
)

func init() {
    flag.StringVar(&srcFile, "sf", "", "要合并的源文件")
    flag.StringVar(&mergeFile, "nf", "", "要合并的新文件")
    flag.StringVar(&outputFile, "of", "./merge-result", "合并之后的文件")
}

func main() {
    flag.Parse()
    if srcFile == "" || mergeFile == "" {
        flag.PrintDefaults()
        os.Exit(1)
    }

    sConfig, err := ReadFile(srcFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    mConfig, err := ReadFile(mergeFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    output, err := os.Create(outputFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    var hzRegexp = regexp.MustCompile("[\u4e00-\u9fa5]+")

    for section, sOptions := range sConfig {
        output.WriteString(fmt.Sprintln(section, "{"))
        mOptions, hasKey := mConfig[section]
        // 忽略不存在的 section
        if !hasKey {
            continue
        }
        ks := make([]string, len(sOptions))
        for k, _ := range sOptions {
            ks = append(ks, k)
        }
        sort.Strings(ks)
        for i := range ks {
            k := ks[i]
            mv, hasKey := mOptions[k]
            // 忽略不存在的配置项
            if !hasKey {
                continue
            }
            t, err := SwitchReflectType(mv)
            if err != nil {
                fmt.Println(err)
                os.Exit(1)
            } else {
                content := fmt.Sprintf("    %s:%s", t, k)
                switch t {
                case "B":
                    content = fmt.Sprintf("%s=%t", content, mv.(bool))
                case "S":
                    // 内容不同的情况下，忽略非中文
                    sv, _ := sOptions[k]
                    if sv != mv && !hzRegexp.MatchString(mv.(string)) {
                        continue
                    }
                    content = fmt.Sprintf("%s=%s", content, mv.(string))
                case "I":
                    content = fmt.Sprintf("%s=%d", content, mv.(int64))
                case "D":
                    content = fmt.Sprintf("%s=%f", content, mv.(float64))
                }

                output.WriteString(fmt.Sprintln(content))
            }
        }
        output.WriteString(fmt.Sprintln("}"))
    }

    // var d interface{}

    // b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
    // json.Unmarshal(b, &d)

    // rv := reflect.ValueOf(d)
    // fmt.Println(rv.Kind())
    // switch rv.Kind() {
    // case reflect.Map:
    //     fmt.Println(rv.MapKeys()[0].Kind())
    // }

    // fmt.Println("success")
}
